<!--
 * @Author: 晟松
 * @Date: 2021-12-05 16:47:48
 * @LastEditors: 晟松
 * @LastEditTime: 2022-02-24 22:54:07
 * @FilePath: \volunteer-vue3-admin\src\views\communityPages\AllResident.vue
 * @Description: 自己所管理的所有居民
-->

<template>
    <div>
        <div class="head">
            <el-row align="middle" justify="start" :gutter="20" class="row">
                <el-col :span="7" class="title">用户名称</el-col>
                <el-col :span="16">
                    <el-input v-model="nameInput" placeholder="请输入用户名称" clearable />
                </el-col>
            </el-row>
            <el-row align="middle" justify="start" :gutter="20" class="row">
                <el-col :span="7" class="title">手机号码</el-col>
                <el-col :span="16">
                    <el-input v-model="phoneInput" placeholder="请输入用户手机号码" clearable />
                </el-col>
            </el-row>
            <el-row align="middle" justify="start" :gutter="20" class="row">
                <el-col :span="7" class="title">用户状态</el-col>
                <el-col :span="16">
                    <el-select v-model="available" class="m-2" placeholder="用户状态" size="large" clearable>
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-col>
            </el-row>
            <el-row align="middle" justify="start" :gutter="20" class="row">
                <el-col :span="20">
                    <el-button type="primary" size="small" @click="serach">搜索</el-button>
                    <el-button type="info" size="small" @click="reset">重置</el-button>
                </el-col>
            </el-row>

            <el-row :gutter="10" class="allBtn">
                <el-col :span="1.1">
                    <el-button type="primary" plain icon="plus" size="mini" @click="handleAdd">新增</el-button>
                </el-col>
                <!-- <el-col :span="1.1">
                    <el-button type="success" plain icon="edit" size="mini" @click="handle">修改</el-button>
                </el-col>-->
                <el-col :span="1.1">
                    <el-button type="danger" plain icon="delete" size="mini" @click="deleteMutiple" :disabled="delDisable">删除</el-button>
                </el-col>
                <el-col :span="1.1">
                    <el-button type="warning" plain icon="upload" size="mini" @click="handleUpload">导入</el-button>
                </el-col>
                <el-col :span="1.1">
                    <el-button type="warning" plain icon="download" size="mini" @click="handleDownload">导出</el-button>
                </el-col>
            </el-row>
        </div>
        <div class="show">
            <el-table :data="data.showList" style="width: 100%" stripe @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column label="id">
                    <template #default="scope">{{ scope.row.id }}</template>
                </el-table-column>
                <el-table-column property="userName" label="姓名" />
                <el-table-column property="phone" label="手机号" align="center" width="150" />
                <el-table-column property="gender" label="性别" show-overflow-tooltip :formatter="genderTrans" />
                <el-table-column property="age" label="年龄" />
                <el-table-column property="detailedAddress" label="详细地址" />
                <el-table-column property="specialDescription" label="特殊说明" width="150" show-overflow-tooltip align="center" />

                <el-table-column label="状态">
                    <template #default="scope">
                        <el-switch v-model="scope.row.available" @change="(val) => switchAvailable(val, scope.row)" />
                    </template>
                </el-table-column>
                <el-table-column property="createdAt" label="创建时间" width="200" align="center" />
                <el-table-column property="timeIntegral" label="时间积分" align="center" />
                <el-table-column align="center" width="230">
                    <template #header>
                        <!-- <el-input v-model="search" size="small" placeholder="Type to search" /> -->
                        操作
                    </template>
                    <template #default="scope">
                        <el-button type="text" size="small" icon="edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button type="text" size="small" icon="delete" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                        <el-button type="text" size="small" icon="lock" @click="handleEditPassword(scope.$index, scope.row)">修改密码</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="demo-pagination-block" :style="{ float: 'right', marginTop: '10px' }">
                <el-pagination
                    :page-size="10"
                    :small="false"
                    :disabled="false"
                    :background="true"
                    layout="total, prev, pager, next"
                    :total="data.total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                ></el-pagination>
            </div>
            <!-- 新增用户 -->
            <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="40%">
                <el-form :model="dialogForm" :label-position="dialogLablePosition" :rules="rules">
                    <el-form-item label="姓名" :label-width="formLabelWidth" prop="userName">
                        <el-input v-model="dialogForm.userName" autocomplete="off" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="性别" :label-width="formLabelWidth">
                        <el-select v-model="dialogForm.gender" placeholder="请选择">
                            <el-option label="男" value="male"></el-option>
                            <el-option label="女" value="female"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
                        <el-input v-model="dialogForm.phone" autocomplete="off" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
                        <el-input v-model="dialogForm.password" autocomplete="off" clearable show-password></el-input>
                    </el-form-item>
                    <el-form-item label="年龄" :label-width="formLabelWidth">
                        <el-input v-model="dialogForm.age" type="number" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="社区" :label-width="formLabelWidth">
                        <el-input v-model="dialogForm.communityName" autocomplete="off" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="详细地址" :label-width="formLabelWidth">
                        <el-input v-model="dialogForm.detailedAddress" autocomplete="off" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="特殊说明" :label-width="formLabelWidth">
                        <el-input v-model="dialogForm.specialDescription" autocomplete="off" clearable></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogFormVisible = false">取消</el-button>
                        <el-button type="primary" @click="addResident">确认</el-button>
                    </span>
                </template>
            </el-dialog>

            <!-- 编辑用户 -->
            <el-dialog v-model="editFormVisible" :title="editFormTitle" width="40%">
                <el-form :model="editForm" :label-position="dialogLablePosition">
                    <el-form-item label="姓名" :label-width="formLabelWidth" prop="userName">
                        <el-input v-model="editForm.userName" autocomplete="off" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="性别" :label-width="formLabelWidth">
                        <el-select v-model="editForm.gender" placeholder="请选择">
                            <el-option label="男" value="male"></el-option>
                            <el-option label="女" value="female"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
                        <el-input v-model="editForm.phone" autocomplete="off" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="年龄" :label-width="formLabelWidth">
                        <el-input v-model="editForm.age" type="number" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="社区" :label-width="formLabelWidth">
                        <el-input v-model="editForm.communityName" autocomplete="off" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="详细地址" :label-width="formLabelWidth">
                        <el-input v-model="editForm.detailedAddress" autocomplete="off" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="特殊说明" :label-width="formLabelWidth">
                        <el-input v-model="editForm.specialDescription" autocomplete="off" clearable></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="editFormVisible = false">取消</el-button>
                        <el-button type="primary" @click="editUser">确认</el-button>
                    </span>
                </template>
            </el-dialog>

            <el-dialog v-model="deleteDialogShow" :title="deleteDialogTitle" width="30%">
                <el-row align="middle">
                    <el-col :span="1">
                        <el-icon color="#E6A23C">
                            <warning-filled />
                        </el-icon>
                    </el-col>
                    <el-col :span="12">
                        <p>是否删除此用户</p>
                    </el-col>
                </el-row>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="deleteDialogShow = false">取消</el-button>
                        <el-button type="primary" @click="handleDeleteStu">确认</el-button>
                    </span>
                </template>
            </el-dialog>

            <el-dialog v-model="editPasswordDialogShow" :title="editPasswordDialogTitle" width="30%">
                <el-row align="middle">
                    <el-col :span="1">
                        <el-icon color="#E6A23C">
                            <warning-filled />
                        </el-icon>
                    </el-col>
                    <el-col :span="12">
                        <p>是否重置密码</p>
                    </el-col>
                </el-row>
                <h4>重置后的密码为手机号后六位</h4>

                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="editPasswordDialogShow = false">取消</el-button>
                        <el-button type="primary" @click="editPassword">确认</el-button>
                    </span>
                </template>
            </el-dialog>

            <el-dialog v-model="uploadDialogShow" :title="uploadDialogTitle" width="400px">
                <el-row justify="center" align="middle">
                    <el-col>
                        <!-- 不要自动上传 -->
                        <el-upload
                            ref="uploadRef"
                            class="upload-demo"
                            drag
                            accept=".xlsx, .xls"
                            action="http://localhost:4000/api/school/batchRegisterResident"
                            :auto-upload="false"
                            :on-success="uploadedSuccess"
                            :on-change="uploadFileChange"
                            :file-list="uploadList"
                        >
                            <el-icon class="el-icon--upload">
                                <upload-filled />
                            </el-icon>
                            <div class="el-upload__text">
                                将文件拖入此处，或
                                <em>点击此处</em>
                            </div>
                            <template #tip>
                                <div class="el-upload__tip">
                                    仅允许导入xls、xlsx格式文件。
                                    <a href="http://qiniu.chengsong.info/testResident.xlsx" target="_blank">下载模板</a>
                                </div>
                            </template>
                        </el-upload>
                    </el-col>
                </el-row>

                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="uploadDialogShow = false">取消</el-button>
                        <el-button type="primary" @click="upload">确认</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup>
import { getAllResident, searchAllResident, batchRegisterResident } from "@/myApi/community";
import { getAllResidentVol } from "@/myApi/vol";
import { getAllSchool, getAllCommunity, create, deleteUser, update, updatePassword } from "../../myApi/user";
import { localFile } from '@/myApi/upload'
import { reactive, ref, computed, onBeforeMount, onMounted, watchEffect } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import enums from "@/utils/enums";
import { ElMessage } from 'element-plus'


let mine = reactive({ resident: { name: "蒋晟松" } });

const store = useStore();
const router = useRouter();
let identity = computed(() => store.getters.identity);
// console.log("identity: ", identity.value);
let userAdmin = computed(() => store.getters.user);
let schoolAdmin = computed(() => store.getters.schoolAdmin);

let nameInput = ref("");
let phoneInput = ref("");
let available = ref(undefined);
let options = [
    {
        value: true,
        label: "正常",
    },
    {
        value: false,
        label: "停用",
    },
];

// 在table中转换一下性别为中文
const genderTrans = (row, column, cellValue, index) => {
    if (cellValue == 'male') {
        return '男'
    } else if (cellValue == 'female') {
        return '女'
    } else {
        return '无'
    }
}

// 存储所有数据的对象
let data = reactive({ allResident: [], showList: [], total: 0 });
let limitOffset = reactive({ limit: 10, offset: 0 });
onMounted(async () => {
    await init()
});
/**
 * @description: 初始化table所需的数据
 * @param {*}
 * @return {*}
 */
async function init() {
    data.allResident = await getAllResident({ id: userAdmin.value.id, limit: limitOffset.limit, offset: limitOffset.offset });
    limitOffset.offset += data.allResident.data.length

    // 这一步主要是获取总的数量
    let res = await getAllResident({ id: userAdmin.value.id })
    data.total = res.data.length
    console.log("data.allResident: ", data.allResident.data);
    data.showList = data.allResident.data
}

const serach = async () => {
    // console.log(nameInput.value, phoneInput.value, available.value);
    // 注意数据格式
    let params = {
        id: userAdmin.value.id,
        userName: nameInput.value,
        phone: phoneInput.value,
        available: available.value
    }
    let res = await searchAllResident(params);
    data.showList = res.data
    console.log('data.showList: ', data.showList);
}

const reset = () => {
    nameInput.value = ''
    phoneInput.value = ''
    available.value = undefined
}

// 修改学生的可用状态
const switchAvailable = async (val, resident) => {
    console.log('val,resident: ', val, resident);
    let res = await update({ id: resident.id, identity: resident.identity, available: val })
    console.log('res: ', res);
}

const multipleSelection = ref([])
/**
 * @description: 处理多行的多选
 * @param {*} val
 * @return {*}
 */
const handleSelectionChange = (val) => {
    console.log('handleSelectionChange val: ', val);
    multipleSelection.value = val
}


let dialogFormVisible = ref(false)
let dialogTitle = '添加居民'
let formLabelWidth = '140px'
let dialogLablePosition = 'left'
let dialogForm = reactive({
    phone: '',
    password: '123456',
    userName: '',
    age: 25,
    gender: 'male',
    identity: 'resident',
    detailedAddress: '',
    specialDescription: '',
    communityName: userAdmin.value.communityName,
    communityId: userAdmin.value.id,
    available: true
})
// 表单校验规则
const rules = reactive({
    userName: [
        {
            required: true,
            message: '请输入姓名',
            trigger: 'blur',
        }
    ],
    phone: [{
        required: true,
        len: 11,
        message: '请正确输入手机号',
        trigger: 'blur',
    }],
    password: [{
        required: true,
        message: '请输入密码',
        trigger: 'blur',
    }, {
        min: 6,
        max: 20,
        message: '长度在6-20',
        trigger: 'blur',
    }]
})
const addResident = async () => {
    console.log('dialogForm: ', dialogForm);
    let res = await create(dialogForm)
    console.log('res: ', res);
    if (res.data.id) {
        dialogFormVisible.value = false;
        // 然后清除dialogForm里的数据，这里就不动了

        // 重新获取列表，需要先修改一下limitOffset里面的offset
        limitOffset.offset = Math.max(limitOffset.offset - 10, 0)
        init();
    } else {
        ElMessage({
            showClose: true,
            message: res.errors[0].message || res.data.text,
            type: 'error',
        })
    }
}

const handleAdd = () => {
    console.log('handleAdd: ', dialogFormVisible.value);
    dialogFormVisible.value = true
}
// 根据是否多选了进行判断是否可删除
let delDisable = computed(() => {
    if (multipleSelection.value.length > 0) return false
    else return true
})
const deleteMutiple = async () => {
    console.log('deleteMutiple: ', multipleSelection.value);
    // 为了后面删除在showLIst里面的对应数据
    let filterArr = ref([])
    for (let i = 0; i < multipleSelection.value.length; i++) {
        let { id, identity } = multipleSelection.value[i]
        filterArr.value.push(id)
        let res = await deleteUser({ id, identity })
        console.log('res: ', res);
    }
    // 进行一个过滤
    data.showList = data.showList.filter(({ id }) => {
        if (filterArr.value.includes(id)) return false
        return true
    })
    // 通过修改limitoffset也是可以实现同样的处理方式
    // await init()
}


let uploadDialogShow = ref(false)
let uploadDialogTitle = ref('批量导入用户')
let uploadList = ref([])
const uploadRef = ref(null)
const handleUpload = () => {
    uploadDialogShow.value = true
}
const upload = async () => {
    // 为什么不适用下面这种方式上传是因为需要特殊处理token的问题，比较麻烦就算了
    // let res = await uploadRef.value.submit()
    console.log('uploadList: ', uploadList.value);
    uploadDialogShow.value = false
}
const uploadFileChange = async (file, List) => {
    console.log('file,List: ', file, List);

    // 注意是formdata的格式，且需要获取原始数据
    let formData = new FormData()
    formData.append('file', file.raw)
    // let res = await fileUpload(formData)

    // 这里上传文件存在本地
    let localSaveRes = await localFile(formData)


    // 这里通过传输文件名自动注册
    formData.append('fileName', localSaveRes.data.key)
    let res = await batchRegisterResident(formData)
    console.log('uploadFileChange res: ', res);
    if (res.data.length > 0) {
        ElMessage({
            showClose: true,
            message: '导入成功',
            type: 'success',
        })
    }

}
const uploadedSuccess = (res, file, fileList) => {
    console.log('res, file, fileList: ', res, file, fileList);
}
const handleDownload = () => {
    console.log('handleDownload: ', dialogFormVisible.value);
}


let editForm = ref({})
let editFormVisible = ref(false)
let editFormTitle = ref('编辑信息')
// 只有校级管理员才可以修改比如学校，学院这一些信息
// let editFormDisabled = ref(schoolAdmin.value)
let editFormDisabled = ref(false)
const handleEdit = (index, resident) => {
    console.log('handleEdit resident: ', resident);
    editForm.value = resident
    editFormVisible.value = true
}
const editUser = async () => {
    let res = await update(editForm.value)
    console.log('res: ', res);
    if (res.data.length > 0) {
        editFormVisible.value = false
    }
}



let deleteDialogShow = ref(false)
let deleteDialogTitle = ref('删除用户')
let deleteIndex = ref(-1)
let deleteStu = reactive({});
const handleDelete = (index, resident) => {
    console.log('handleDelete resident: ', index, resident);
    deleteDialogShow.value = true
    // 从这里分为两步走
    deleteIndex.value = index
    deleteStu = resident
}
const handleDeleteStu = async () => {
    let { id, identity } = deleteStu
    // 这里才是真正的删除用户
    let res = await deleteUser({ id, identity })
    data.showList.splice(deleteIndex.value, 1)
    deleteDialogShow.value = false
}

let editPasswordDialogShow = ref(false)
let editPasswordDialogTitle = ref('修改密码')
let editPasswordStr = ref('')
let editPasswordStu = reactive({});
const handleEditPassword = (index, resident) => {
    console.log('handleEditPassword resident: ', resident);
    editPasswordDialogShow.value = true
    // 取手机号后六位
    editPasswordStr.value = resident.phone.slice(-6)
    editPasswordStu = resident

}
const editPassword = async () => {
    let { id, identity } = editPasswordStu
    let res = await updatePassword({ id, identity, password: editPasswordStr.value })
    // console.log('res: ', res);
    editPasswordDialogShow.value = false
}

// 分页所需的东西
const handleSizeChange = (val) => {
    console.log(`${val} items per page`)
}
const handleCurrentChange = async (val) => {
    console.log(`current page: ${val}`)
    // 注意这里是 val-1
    let offset = (val - 1) * limitOffset.limit
    let res = {}
    res = await getAllResident({ id: userAdmin.value.id, limit: limitOffset.limit, offset })
    data.showList = res.data.data
}

</script >

<style lang="scss" scoped>
.head {
    display: flex;
    // justify-content: space-around;
    flex-wrap: wrap;
    .allBtn {
        margin: 10px;
    }
    .row {
        margin: 0 10px;
        min-width: 20vw;
        .title {
            font-size: 0.9rem;
            font-weight: bold;
        }
    }
}
.show {
    .optionBtn {
    }
}
</style>
